package com.zjt.smart.util;

import android.text.TextUtils;

import com.zjt.smart.util.encrypt.DESCoder;
import com.zjt.smart.util.encrypt.RSACoder;

/**
 * @author zhengjianting
 * @time 2017/8/25 0025 上午 11:21
 */

public class SecurityUtil {

    /**
     * rsa私钥解密
     *
     * @param str
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String rsaDecode(String str, String privateKey)
            throws Exception {
        byte[] decodedData = RSACoder.decryptByPrivateKey(
                RSACoder.decryptBASE64(str), privateKey);
        return new String(decodedData);
    }

    /**
     * DES解密
     *
     * @return 解密后的字符串
     * @throws Exception
     */
    public static String desDecode(String decryptString, String decryptKey)
            throws Exception {
        return DESCoder.decryptDES(decryptString, decryptKey);
    }

    public static String escape(String src) {
        if (TextUtils.isEmpty(src)) {
            return null;
        }
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);

        for (i = 0; i < src.length(); i++) {

            j = src.charAt(i);

            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j))
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16)
                    tmp.append("0");
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }
}
